 /**
 * @author caif
 * @fileoverview 3D viewer plugin
 */
;(function(){
   TViewer = {
       initViewer : function(){
		     if(this.gViewerInited) return;
		     var gViewer = this.createViewer("100%", "100%", document.getElementById("3D-Viewer"), "3D-Viewer");
		     $("#databag-img-content").show();
		     if($.browser.msie){
		     	if(typeof gViewer._version === 'undefined'){
	     			if(window.navigator.platform.toLowerCase() === 'win64'){
	     			   this.addInstallIE64Tip(gViewer);
	     			}else{
	     			   this.addInstallTip(gViewer);
	     			}
		     		return;
	     		}else if(gViewer._version !== '1.0.0.1'){
	     			this.addNewPluginTip(gViewer);
	     			return;
	     		}
		     }else{
		     	var pluginDescription = this.getPlugin('Jetfire 3D ModelViewer');
		     	if(pluginDescription === false){
		     		//not installed
		     		this.addInstallTip(gViewer);
		     		return;
		     	}else{
		     		var version = pluginDescription.split(' ').pop();
		     		if(pluginDescription !=='Jetfire 3D ModelViewer for BIM/Construction' && version !== 'V1.0.0.1'){
		     			//new plugin is available
		     			this.addNewPluginTip(gViewer);
		     			return;
		     		}
		     	}
		     }
             gViewer.addNotificationListener("selection_changed", this.onSelectionChanged );
             gViewer.addNotificationListener("viewpoint_required", this.onViewPointRequired);
             gViewer.addNotificationListener("viewpoint_created", this.onViewPointCreated);
             gViewer.addNotificationListener("viewpoint_deleted", this.onViewPointDeleted);
             gViewer.addNotificationListener("viewpoint_changed", this.onViewPointChanged);
             gViewer.addNotificationListener("action_activated", this.onActionChanged);
             gViewer.addNotificationListener("action_deactivated", this.onActionChanged);
             gViewer.addNotificationListener("show_element_info", this.onNotified);
             gViewer.addNotificationListener("enter_gravity_zone", this.onEnterGravityZone);
     
             gViewer.execCommand("setOptions", "viewPointRequired:false");
    
            // 添加构件类型
             gViewer.execCommand("addElementSchema", "#1:$wall:墙:0xc0c0c0:12:0");
             gViewer.execCommand("addElementSchema", "#2:$beam:梁:0x008080:8:3");
             gViewer.execCommand("addElementSchema", "#3:$slab:板:0xd3d3d3:16:1");
             gViewer.execCommand("addElementSchema", "#4:$column:柱:0xd2b48c:4:2");
             gViewer.execCommand("addElementSchema", "#5:$door:门:0x786495ed:8:4");
             gViewer.execCommand("addElementSchema", "#6:$window:窗:0x646495ed:8:4");
             gViewer.execCommand("addElementSchema", "#7:$opening:洞口:0xffffff:20:5");
             gViewer.execCommand("addElementSchema", "#8:$stair:楼梯:0xffffff:20:5");
             gViewer.execCommand("addElementSchema", "#9:$pipe:管道:0xffff00:20:5");
             gViewer.execCommand("configElement", "#0:0xff0000:20:5");
        	 
             this.updateUI();
             this.gViewer = gViewer;
             this.gViewerInited = true;
		 }
		 ,
		 open : function( path , extension ,  dataBagId ){
		 	 if(!this.gViewerInited) return;
		 	 var self = this;
		     var extensionFlag;
             if( extension.toUpperCase() == "GMSB" )
             {
                 extensionFlag = 0;
             }
             else if( extension.toUpperCase() == "IFC" )
             {
                 extensionFlag = 1;
             }
             else if( extension.toUpperCase() == "GCL9" )
             {
                 extensionFlag = 2;
             }
             else if( extension.toUpperCase() == "JFX" )
             {
                 extensionFlag = 3;
             }
             var url = window.location.protocol + '//' + window.location.host + "/databag/bag/" + dataBagId + "/path/" + path +"\0";
         	 if($.browser.msie){
                self.gViewer.open(url, extensionFlag ,false )
        	 }else{
                self.gViewer.open(url, extensionFlag ,false , self.getCookie("JSESSIONID"));
             }
		 },
		 
		 getData: function(path, extension, dataBagId){
		 	 var self = this;
		 	 var url = window.location.protocol + '//' + window.location.host + "/databag/bag/" + dataBagId + "/path/" + path +"\0";
         	 if(self.previousUrl === url){
         	 	$('#thumbnails, #flash-wrap, #databag-img').hide();
         	 	$("#3D-Viewer-wrap, #databag-img-header").show();
         	 	return;
         	 }
             $('#loading-cover').show();
             $.get(url, function(data){
             	$('#loading-cover, #thumbnails, #flash-wrap, #databag-img').hide();
             	$("#3D-Viewer-wrap, #databag-img-header").show();
             	self.initViewer();
             	self.open(path, extension, dataBagId);
             	self.previousUrl = url;
             });
		 },
		 
		 addIE64BitTip: function(gViewer){
		 	$(gViewer).hide();
		 	$('<div class="dl-3dviewer" id="dl-3dviewer"><p class="ie-64bit-tip">暂不支持 64 位版本的 IE，请选择 32 位的版本（在开始菜单里面选择不带 "64 位"字样的 IE）</p></div>')
     		.insertAfter('#3D-Viewer');
		 },
		 addInstallIE64Tip: function(gViewer){
            $(gViewer).hide();
            $('<div class="dl-3dviewer" id="dl-3dviewer"><a href="/databag/resource/Jetfire_Plugin_x64.exe" target="_self" class="dl-btn">请点击安装插件</a></div>')
            .insertAfter('#3D-Viewer');
         },
		 addInstallTip: function(gViewer){
		 	$(gViewer).hide();
		 	$('<div class="dl-3dviewer" id="dl-3dviewer"><a href="/databag/resource/Jetfire_Plugin.exe" target="_self" class="dl-btn">请点击安装插件</a></div>')
     		.insertAfter('#3D-Viewer');
		 },
		 
		 addNewPluginTip: function(gViewer){
		 	$(gViewer).hide();
		 	$('<div class="dl-3dviewer" id="dl-3dviewer"><a href="/databag/resource/Jetfire_Plugin.exe" target="_self" class="dl-btn">请更新插件</a></div>')
     		.insertAfter('#3D-Viewer');
		 },
		 
		 /**
		  * @description only for firefox and chrome
         *  @param {String} cookieName get cookie of firefox or chrome
        */
		 getCookie : function ( cookieName ) {
            var cookieString = document.cookie;
            var start = cookieString.indexOf(cookieName + '=');
            if (start == -1)
            {
                return null;
            } 
            
            start += cookieName.length + 1;
            var end = cookieString.indexOf(';', start);
            if (end == -1) return unescape(cookieString.substring(start));
            return unescape(cookieString.substring(start, end));
         }
         ,
         
         /**
         *  @param {String} width width of viewer  
         *  @param {String} height height of viewer 
         *  @param {String} placeholder placeholder of viewer
         *  @param {String} viewerId viewerId of viewer
        */
		 createViewer : function( width, height, placeholder, viewerId )
		 {
		    var viewer = null;
            if ($.browser.msie) {
            	viewer = $("<object/>").attr({
            		"id" : viewerId,
            		"classid" : "clsid:8d5be3d9-7abb-45a4-9158-750c9446e8e7",
            		"width": width,      
            		"height": height,
            		'wmode': 'transparent'
            	})[0];
            } else {
            	viewer = $("<embed/>").attr({
            		"id" : viewerId,
            		"type" : "application/jfview-plugin",
            		"width": width,      
            		"height": height,
            		'wmode': 'transparent'
            	})[0];
            }
            $("#"+viewerId).append( $("<div id='three-property'></div>") );
            this.createIframe(placeholder, viewer);
            return viewer;
		 }
		 ,
		 createIframe: function(placeholder, viewer){
		 	var iframe = $('<iframe frameborder="0" style="width:100%;height:100%;"></iframe>').appendTo(placeholder),
            iframeWin = iframe[0].contentWindow,
            iframeDoc = iframe[0].contentDocument || iframeWin.document;
            iframeDoc.open();
			iframeDoc.write('');
			iframeDoc.close();
           	iframeDoc.body.appendChild(viewer);
           	iframeDoc.body.style.overflow = 'hidden';
           	iframeDoc.body.style.margin = '2px';
		 }
		 ,
		 updateUI :  function( )
		 {
		     
		 }
		 ,
		 onSelectionChanged : function(sender, code, data) {
			
         }
        ,
        onViewPointRequired : function (sender, code, data) {
            this.createViewPoint();
        }
        ,
        onViewPointCreated : function (sender, code, data) {
            this.createViewPointUI(data);
        }
        ,
        onViewPointDeleted : function(sender, code, data) {
            this.deleteViewPointUI(data);
        }
        ,
        onViewPointChanged : function(sender, code, data) {
            var arr = data.split(":");
            var vid = arr[0].substr(1);
            
            var imgData = this.gViewer.execCommand("createScreenshot", "100:75");
            var img = document.getElementById("vpImage_" + vid);
            img.src = "data:image/png;base64," + imgData;
            
            if (arr[1] != null && arr[1].length > 0) {
                var vpCamera = document.getElementById("vpCamera_" + vid);
                if (vpCamera != null) {
                    vpCamera.innerHTML = arr[1];
                }
            }
            
            if (arr[2] != null) {
                var vpRedMarks = document.getElementById("vpRedMarks_" + vid);
                    if (vpRedMarks != null) {
                        vpRedMarks.innerHTML = arr[2];
                    }
                }
            }
        ,
        onActionChanged : function(sender, code, data) {
           // updateUI();
        }
        ,
        onNotified : function(sender, code, data) {
			$.ajax({
				url : "/databag/rvt/" + parent.$(".databag-flag").attr("databagid") + "/" + data,
				success : function(data)
				{
					var id = data.Id,
		        	name = data.Name,
		        	properties = data.Properties,
		        	tpl ="<div class='propertyWrap'>" +
		        			"<div class='propertyName'></div>" + 
							"<div class='propertyDetail'>" +
								"<div class='propertyKey'></div>" +
								"<div class='propertyValue'></div>" +
							"</div>  "+ 
						 "</div>";
					$("#three-property").empty();
		        	for( var key in properties  )
		        	{
		        		var content =  $(tpl);
		        		content.find(".propertyName").html(key);
		        		for(var pro in properties[key])
		        		{
		        			
		        			content.find(".propertyKey").html(pro);
		        			content.find(".propertyValue").html(properties[key][pro]);
		        			$("#three-property").append( content );
		        		}
		        	}
				}
			    ,
			    error : function(){
			    	
			    }
			})
        }
        ,
        onEnterGravityZone : function(sender, code, data) {
        	
        },
        
        getPlugin: function(name){
	      	name = name.toLowerCase();
	      	for(var i = 0; i < navigator.plugins.length; i++){
	            if(navigator.plugins[i].name.toLowerCase().indexOf(name) > -1){
                   return navigator.plugins[i].description;
	            }
	      	}
	       	return false;
		}
   }; 
})()
